//
//  AppDelegate.m
//  KFD
//
//  Created by JIRENTIANXIANG on 6/8/15.
//  Copyright (c) 2015 kfd. All rights reserved.
//

#import "AppDelegate.h"
#import "KFDTabBarController.h"
#import <Onboard/OnboardingContentViewController.h>
#import <Onboard/OnboardingViewController.h>
#import "KFDAccountManager.h"
#import "KFDReachability.h"
#import "ui_config.h"
#import "GeTuiSdk.h"
#import "NSDate+format.h"
#import "JTToast.h"
#import "KFDNotificationParser.h"
#import "KFDChatViewController.h"
#import "KFDSettingsManager.h"
#import <AudioToolbox/AudioToolbox.h>

#import "MobClick.h"

#define NotifyActionKey "NotifyAction"

NSString* const NotificationCategoryIdent  = @"ACTIONABLE";
NSString* const NotificationActionOneIdent = @"ACTION_ONE";
NSString* const NotificationActionTwoIdent = @"ACTION_TWO";

static NSString *const UMengAppKey = @"56932acd67e58e528c0017d9";
static NSString *const UMengChannelID = @"";

@interface AppDelegate ()

@property (strong,nonatomic) UITabBarController* tabBarController;
@property (strong,nonatomic) KFDReachability* reachability;

@property (strong,nonatomic) NSTimer* alarmRepeatTimer;
@property (strong,nonatomic) NSTimer* alarmDurationTimer;

@end

@implementation AppDelegate
{
    BOOL _shou;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [self.alarmRepeatTimer invalidate];
    [self.alarmDurationTimer invalidate];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [self.reachability stopNotifiers];

}

//--------------------------------------------------------------------------------------
// Getui
//--------------------------------------------------------------------------------------
- (void)registerRemoteNotification {
    
#ifdef __IPHONE_8_0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        //IOS8 新的通知机制category注册
        UIMutableUserNotificationAction *action1;
        action1 = [[UIMutableUserNotificationAction alloc] init];
        [action1 setActivationMode:UIUserNotificationActivationModeBackground];
        [action1 setTitle:@"取消"];
        [action1 setIdentifier:NotificationActionOneIdent];
        [action1 setDestructive:NO];
        [action1 setAuthenticationRequired:NO];
        
        UIMutableUserNotificationAction *action2;
        action2 = [[UIMutableUserNotificationAction alloc] init];
        [action2 setActivationMode:UIUserNotificationActivationModeBackground];
        [action2 setTitle:@"回复"];
        [action2 setIdentifier:NotificationActionTwoIdent];
        [action2 setDestructive:NO];
        [action2 setAuthenticationRequired:NO];
        
        UIMutableUserNotificationCategory *actionCategory;
        actionCategory = [[UIMutableUserNotificationCategory alloc] init];
        [actionCategory setIdentifier:NotificationCategoryIdent];
        [actionCategory setActions:@[action1, action2]
                        forContext:UIUserNotificationActionContextDefault];
        
        NSSet *categories = [NSSet setWithObject:actionCategory];
        UIUserNotificationType types = (UIUserNotificationTypeAlert|
                                        UIUserNotificationTypeSound|
                                        UIUserNotificationTypeBadge);
        
        UIUserNotificationSettings *settings;
        settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|
                                                                       UIRemoteNotificationTypeSound|
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
#else
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|
                                                                   UIRemoteNotificationTypeSound|
                                                                   UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif
    
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self registerSound];
    
    [MobClick startWithAppkey:UMengAppKey reportPolicy:BATCH channelId:UMengChannelID];
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    
//    NSString* note=@"id=0&type=2&msg=您关注的泸深300价格涨到100了，快来查看&sound=1&time=60&shock=1";
//    KFDNotification* notification=[KFDNotificationParser parseNote:note];
//    
//    self.reachability=[KFDReachability sharedReachability];
//    [self.reachability startNotifiers];
    
    KFDAccountManager* manager=[KFDAccountManager sharedManager];
    [manager loginLastSession];
    
    // [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
    
    // [2]:注册APNS
    [self registerRemoteNotification];
    
    // [2-EXT]: 获取启动时收到的APN数据
    NSDictionary* message = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (message) {
        NSString *payloadMsg = [message objectForKey:@"payload"];
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
    }
    
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // [EXT] APP进入后台时，通知个推SDK进入后台
    [GeTuiSdk enterBackground];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    // [EXT] 重新上线
    [self startSdkWith:_appID appKey:_appKey appSecret:_appSecret];
    
    UITabBarController* tab=self.tabBarController;
}
-(void) stopSdk {
    [GeTuiSdk enterBackground];
}

#pragma mark - background fetch  唤醒
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    //[5] Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    _deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"deviceToken:%@", _deviceToken);
    
    // [3]:向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:_deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    // [3-EXT]:如果APNS注册失败，通知个推服务器
    [GeTuiSdk registerDeviceToken:@""];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userinfo {
    // [4-EXT]:处理APN
    NSString *payloadMsg = [userinfo objectForKey:@"payload"];
    if (payloadMsg) {
//        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
//        [[JTToast makeText:payloadMsg] showInView:self.window size:CGSizeMake(payloadMsg.length*20, 40)];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // [4-EXT]:处理APN
//    NSString *payloadMsg = [userInfo objectForKey:@"payload"];
//    
//    NSDictionary *aps = [userInfo objectForKey:@"aps"];
//    NSNumber *contentAvailable = aps == nil ? nil : [aps objectForKeyedSubscript:@"content-available"];
    
//    if (payloadMsg && contentAvailable) {
//        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@, [content-available: %@]", [NSDate date], payloadMsg, contentAvailable];
//    }
    
//    NSString* alert=aps[@"alert"];
//    KFDNotification* note=[KFDNotificationParser parseNote:alert];
    NSString* value=userInfo[@"value"];
    NSArray* arr=[value componentsSeparatedByString:@":"];
    KFDSettingsManager* settingsManager=[KFDSettingsManager sharedManager];
    if (arr.count==2) {
        if ([arr.lastObject isEqualToString:@"3"]) {
            self.chatUrl=[NSString stringWithFormat:@"http://kfd.demo.golds-cloud.com/m-pm?id=%@",arr.firstObject];
            [[NSNotificationCenter defaultCenter] postNotificationName:KFDChatNotification object:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                KFDMessageNotificationSettings* settings=settingsManager.messageNotificationSettings;
                if (settings.masterSwitch) {
                    if (settings.sound) {
                        [self playSoundVibrated:settings.vibration];
                    }
                }
            });
        }else if ([arr.lastObject isEqualToString:@"2"]){
            dispatch_async(dispatch_get_main_queue(), ^{
                self.alarmRepeatTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playAlarm) userInfo:nil repeats:YES];
                [settingsManager getAlarmRingtoneSettingsWithSuccessHandler:^(KFDAlarmRingtoneSettings *settings) {
                    int duration=settings.notice_time.intValue;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.alarmDurationTimer=[NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(stopAlarm) userInfo:nil repeats:NO];
                    });
                } failureHandler:nil];
            });
        }
    }
    
//    switch () {
//        case 1:
//            break;
//        case 2:
//            break;
//        case 3:
//        {
//            self.chatUrl=[NSString stringWithFormat:@"http://kfd.demo.golds-cloud.com/m-pm?id=%@",note.id];
//            [[NSNotificationCenter defaultCenter] postNotificationName:KFDAPNParsedNotification object:nil];
//        }
//            break;
//        default:
//            break;
//    }
    completionHandler(UIBackgroundFetchResultNewData);
}

-(void)playAlarm
{
    KFDSettingsManager* settingsManager=[KFDSettingsManager sharedManager];
    KFDAlarmRingtoneSettings* settings=settingsManager.alarmRingtoneSettings;
    [self playSoundVibrated:settings.shock];
}

-(void)stopAlarm
{
    [self.alarmRepeatTimer invalidate];
}

- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret
{
    
    _appID = appID;
    _appKey = appKey;
    _appSecret = appSecret;
    
    NSError *err = nil;
    
    //[1-1]:通过 AppId、 appKey 、appSecret 启动SDK
    [GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self error:&err];
    
    //[1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:YES];
    //[1-3]:设置电子围栏功能，开启LBS定位服务 和 是否允许SDK 弹出用户定位请求
    [GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
    
    if (err) {
    }
}

- (void)setDeviceToken:(NSString *)aToken
{
    
    [GeTuiSdk registerDeviceToken:aToken];
}

- (BOOL)setTags:(NSArray *)aTags error:(NSError **)error
{
    return [GeTuiSdk setTags:aTags];
}

- (NSString *)sendMessage:(NSData *)body error:(NSError **)error {
    
    return [GeTuiSdk sendMessage:body error:error];
}

- (void)bindAlias:(NSString *)aAlias {
    [GeTuiSdk bindAlias:aAlias];
}

- (void)unbindAlias:(NSString *)aAlias {
    
    [GeTuiSdk unbindAlias:aAlias];
}

#pragma mark - GexinSdkDelegate
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId
{
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    _clientId = clientId;
    
    if (_deviceToken) {
        [GeTuiSdk registerDeviceToken:_deviceToken];
    }
}

- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId fromApplication:(NSString *)appId
{
    // [4]: 收到个推消息
    _payloadId = payloadId;
    
    NSData* payload = [GeTuiSdk retrivePayloadById:payloadId];
    
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length
                                            encoding:NSUTF8StringEncoding];
        
    }
    
//    NSString *record = [NSString stringWithFormat:@"%d, %@, %@", ++_lastPayloadIndex, [self formateTime:[NSDate date]], payloadMsg];
//    
//    NSLog(@"task id : %@, messageId:%@", taskId, aMsgId);
    
}

- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // [4-EXT]:发送上行消息结果反馈
    NSString *record = [NSString stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
}

- (void)GeTuiSdkDidOccurError:(NSError *)error
{
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
}

- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // [EXT]:通知SDK运行状态
    _sdkStatus = aStatus;
}

//SDK设置推送模式回调
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    if (error) {
        return;
    }
}

-(NSString*) formateTime:(NSDate*) date {
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH:mm:ss"];
    NSString* dateTime = [formatter stringFromDate:date];
    return dateTime;
}

static void uncaughtExceptionHandler(NSException *exception) {
    NSLog(@"CRASH: %@", exception);
    NSLog(@"Stack Trace: %@", [exception callStackSymbols]);
}

//--------------------------------------------------------------------------------------

static SystemSoundID new_message_sound_id = 0;

-(void)registerSound
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"new_message" ofType:@"wav"];
    if (path) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&new_message_sound_id);
    }
}

-(void) playSoundVibrated:(BOOL)vibrated
{
    AudioServicesPlaySystemSound(new_message_sound_id);
    if(vibrated){
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
    }
}

@end
